%%%-------------------------------------------------------------------
%%% @author Viktor Green <viktor@student.gu.se>
%%% @copyright (C) 2011, Viktor Green
%%% @doc
%%% Gen server for receiving data from peers
%%% @end
%%% Created : 16 Dec 2011 by Viktor Green <viktor@student.gu.se>
%%%-------------------------------------------------------------------
-module(peer_recv).

-behaviour(gen_server).

%% API
-export([start_link/1]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).

-define(SERVER, ?MODULE). 

-record(state, {socket :: gen_tcp:socket()}).

%%%===================================================================
%%% API
%%%===================================================================

%%--------------------------------------------------------------------
%% @doc
%% Starts the server
%%
%% @end
%%--------------------------------------------------------------------
-spec start_link(Socket :: gen_tcp:socket()) ->
			{ok, Pid :: pid()} |
			ignore |
			{error, Error :: term()}.
start_link(Socket) ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [Socket], []).

%%%===================================================================
%%% gen_server callbacks
%%%===================================================================

%%--------------------------------------------------------------------
%% @private
%% @doc
%% Initializes the server
%%
%% @spec init(Args) -> {ok, State} |
%%                     {ok, State, Timeout} |
%%                     ignore |
%%                     {stop, Reason}
%% @end
%%--------------------------------------------------------------------
init([Socket]) ->
    {ok, #state{socket = Socket}}.

%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling call messages
%%
%% @spec handle_call(Request, From, State) ->
%%                                   {reply, Reply, State} |
%%                                   {reply, Reply, State, Timeout} |
%%                                   {noreply, State} |
%%                                   {noreply, State, Timeout} |
%%                                   {stop, Reason, Reply, State} |
%%                                   {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_call(_Request, _From, State) ->
    Reply = ok,
    {reply, Reply, State}.

%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling cast messages
%%
%% @spec handle_cast(Msg, State) -> {noreply, State} |
%%                                  {noreply, State, Timeout} |
%%                                  {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_cast(_Msg, State) ->
    {noreply, State}.

%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling all non call/cast messages
%%
%% @spec handle_info(Info, State) -> {noreply, State} |
%%                                   {noreply, State, Timeout} |
%%                                   {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_info({tcp, Socket, Data}, #state{socket = Socket} = State) ->
    incomming_data(Data),
    {noreply, State};
handle_info({tcp_closed, Socket}, #state{socket = Socket} = State) ->
    {stop, normal, State};
handle_info(_Info, State) ->
    {noreply, State}.

%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
%%
%% @spec terminate(Reason, State) -> void()
%% @end
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
    ok.

%%--------------------------------------------------------------------
%% @private
%% @doc
%% Convert process state when code is changed
%%
%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%%%===================================================================
%%% Internal functions
%%%===================================================================

%%--------------------------------------------------------------------
%% @doc
%% Handle incomming data
%% @end
%%--------------------------------------------------------------------
-spec incomming_data(Data :: binary()) -> ok.
incomming_data(Data) ->
    case Data of
	<<0:32/integer>> ->
	    io:format("Keep-alive~n");
	<<Length:32/integer, Value/binary>> ->
	    case Length < byte_size(Value) of
		true -> 
		    <<Rest:Length/binary, Next/binary>> = Value,
		    parse_msg(Rest),
		    incomming_data(Next);
		false ->
		    parse_msg(Value)
	    end;
	<<Other/binary>> ->
	    io:format("Unknown thing: ~p ~n", [Other])
    end.


parse_msg(Data) ->
    case Data of
	<<0:8/integer>> ->
	    io:format("Choke~n");
	<<1:8/integer>> ->
	    io:format("UnChoke~n");
	<<2:8/integer>> ->
	    io:format("Interested ~n");
	<<3:8/integer>> ->
	    io:format("NotInterested ~n");
	<<4:8/integer, HaveIndex:32/integer>> ->
	    io:format("Have: ~p~n", [HaveIndex]);
	<<5:8/integer, Bitfield/binary>> ->
	    io:format("Bitfield: ~p~n", [Bitfield]);
	<<6:8/integer, ReqInd:32/integer,
	  ReqBeg:32/integer, ReqLen:32/integer>> ->
	    io:format("Request: ~p, ~p, ~p", [ReqInd, ReqBeg, ReqLen]);
	<<7:8/integer, PieInd:32/integer,
	  PieBeg:32/integer, Piece/binary>> ->
	    io:format("Piece: ~p, ~p~n~p~n", [PieInd, PieBeg, Piece]);
	<<8:8/integer, CanInd:32/integer,
	  CanBeg:32/integer, CanLen:32/integer>> ->
	    io:format("Cancel: ~p, ~p, ~p", [CanInd, CanBeg, CanLen]);
	<<Other/binary>> ->
	    io:format("Unknown message: ~p~n", [Other])
    end.

